package com.ellen.mac.chatdemo.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Toast;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.AVUser;
import com.avos.avoscloud.im.v2.AVIMClient;
import com.avos.avoscloud.im.v2.AVIMConversation;
import com.avos.avoscloud.im.v2.AVIMException;
import com.avos.avoscloud.im.v2.callback.AVIMClientCallback;
import com.avos.avoscloud.im.v2.callback.AVIMConversationCreatedCallback;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.ellen.mac.chatdemo.R;
import com.ellen.mac.chatdemo.adpter.UserInfoAdapter;
import com.ellen.mac.chatdemo.cache.ACache;
import com.ellen.mac.chatdemo.comment.BaseApp;
import com.ellen.mac.chatdemo.utils.LogUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created by aven on 2017/12/1.
 * leancloud 存储
 */

public class StorageAct extends AppCompatActivity {
    RecyclerView mRecyclerView;
    private UserInfoAdapter userInfoAdapter;
    List<AVUser> users;
    private ACache mCache;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.storage_act);
        initView();
    }

    private void initView() {
        mCache = ACache.get(this);
        users = new ArrayList<>();
        userInfoAdapter = new UserInfoAdapter(R.layout.userinfo_item, users);
        mRecyclerView = (RecyclerView) findViewById(R.id.rv_list);
        GridLayoutManager layoutManage = new GridLayoutManager(this, 1);
        mRecyclerView.setLayoutManager(layoutManage);
        userInfoAdapter.openLoadAnimation(BaseQuickAdapter.SLIDEIN_BOTTOM);
        mRecyclerView.setAdapter(userInfoAdapter);
        mRecyclerView.addOnItemTouchListener(new OnItemChildClickListener() {
            @Override
            public void onSimpleItemChildClick(BaseQuickAdapter adapter, View view, int position) {

                //1 创建聊天室
                createChatRoom(users.get(position).getUsername());
            }
        });
    }

    private void createChatRoom(final String name) {
        String UserName = mCache.getAsString(BaseApp.USERNAME);
        AVIMClient client = AVIMClient.getInstance(UserName);
        client.open(new AVIMClientCallback() {
            @Override
            public void done(AVIMClient client, AVIMException e) {
                if (e == null) {
                    client.createConversation(Arrays.asList(name), name, null, false, true,
                            new AVIMConversationCreatedCallback() {
                                @Override
                                public void done(AVIMConversation conversation, AVIMException e) {
                                    if (e == null) {
                                        Toast.makeText(StorageAct.this, "Room Create Success id is " + conversation.getConversationId(), Toast.LENGTH_SHORT).show();
                                        //todo 跳转到聊天室
                                        Intent intent = new Intent(StorageAct.this, ChatRoomAct.class);
                                        intent.putExtra(BaseApp.CONVERSATION_ID, conversation.getConversationId());
                                        startActivity(intent);
                                    }
                                }
                            });
                }
            }
        });
    }

    public void findUser(View v) {
        new Thread() {
            public void run() {
                // tips:网络请求不能在主线程
                AVQuery<AVUser> userQuery = new AVQuery<>("_User");
                try {
                    users = userQuery.find();
                    Message msg = new Message();
                    Bundle data = new Bundle();
                    data.putString("userInfo", "ok");
                    msg.setData(data);
                    handler.sendMessage(msg);

                } catch (AVException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Bundle data = msg.getData();
            if (data.getString("userInfo").equals("ok")) {
                for (int i = 0; i < users.size(); i++) {
                    LogUtils.i("username==" + users.get(i).getUsername());
                }
                userInfoAdapter.setNewData(users);
                userInfoAdapter.notifyDataSetChanged();
            }
        }
    };
}
